//
// Created by 123 on 2024/12/26.
//
#include "stdio.h"

int main074(){
    FILE* fp;
    //以写入模式打开文件
    fp = fopen("test.txt","w");
    if(fp == NULL){
        perror("open file failure\n");
        return 1;
    }
    //使用fprint写入格式化的数据
    fprintf(fp,"name:%s\n","hary");
    fprintf(fp,"age:%d\n",20);
    fprintf(fp,"score:%.2f\n",88.5);
    //使用fputs写入字符串
    fputs("this is a test file\n",fp);

    //关闭文件
    fclose(fp);

    //读取文件
    FILE* file;
    char buffer[100];
    char name[50];
    int age;
    float score;
    //以读模式打开文件
    file = fopen("test.txt","r");
    if(file == NULL){
        perror("open file failure");
        return 1;
    }
    //输出内容
    printf("=============== fgets read contents===============\n");
    while (fgets(buffer,sizeof(buffer),file) != NULL){
        printf("%s",buffer);
    }
    //重置文件指针到文件开头
    rewind(file);
    //使用fscanf读取格式化数据
    printf("=============== fscanf read format contents:===============\n");
    fscanf(file,"name:%s\n",name);
    fscanf(file,"age:%d\n",&age);
    fscanf(file,"score:%f\n",&score);

    printf("name:%s\n",name);
    printf("age:%d\n",age);
    printf("score:%.2f\n",score);

    fclose(file);
    return 0;
}